Odin Basic Grammars
Table of Contents
1. Control Flows
1.1. if statement and when statement
when statement is compile-time if statement. Similar to if constexpr in C++.
1.2. Switch Statement
Unlike C++, Odin’s switch only executes 1 branch, the selected branch.
2. Resource clean up with defer
The defer statement defers the execution of a statement until the end of the scope it is in. defer statement are executed in the reverse order that they were declared. In addition, we can also defer entire block or if statement.
main :: proc() {
x := 123
defer fmt.println(x)
{
defer x = 4
x = 2
}
fmt.println(x) // print 4
x = 234
} // print 234
3. Parameters
The calling convention is the same as C, but
- it promotes values to a pointer if it’s more efficient
- it includes a pointer to the current context as an implicit additional argument
All parameters are immutable.
3.1. Variadic Parameters
sum :: proc(nums: ..int) -> (result: int) {
for n in nums do result += n
return
}
fmt.println(sum()) // -> 0
fmt.println(sum(1,2,3)) // -> 6
odds := []int{1, 3, 5}
fmt.println(sum(..odds)) // -> 9, passing a slice as varargs
3.2. Multiple Results
Results are returned in tuple-like syntax (swap :: proc(x, y: int) -> (int, int)) and can be unpacked with a,b := swap(1,2)
3.3. Named Results
Define the variable to return in declaration, not with return statement. Like in Solidity. It’s also possible to give default value for returned value.
3.4. Named Arguments
As in Python, call the procedure with explicit argument arg=value.
4. Type Conversion
We can use T(var) or cast(T) var to convert var into type T, which can also be done with auto_cast var operator.
transmute(T) var is a bit cast conversion, similar to reinterpret_cast<T>(var).
4.1. Addresses
^T denotes pointer type that points to a value of type T. &x generates a pointer of ^T to x. x^ is dereferencing.